﻿using Avalonia.Controls;
using LightCAD.Core;
using LightCAD.Core.Elements;
using LightCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using static LightCAD.Core.Elements.LcPolyLine;

namespace LightCAD.Drawing.Actions
{

    public class RectangAction : ElementAction
    {
        public static string CommandName;
        public static LcCreateMethod[] CreateMethods;
        private List<Vector2> points;
        /// <summary>
        /// 多段线第一个点
        /// </summary>
        private Vector2? startPoint { get; set; }
        /// <summary>
        /// 每节线的开始点
        /// </summary>
        private Vector2? firstPoint { get; set; }
        /// <summary>
        /// 每节线的第二个点
        /// </summary>
        private Vector2? secondPoint { get; set; }
        /// <summary>
        /// 零时集合
        /// </summary>
        private List<PlineSegment> Segments { get; set; }


        static RectangAction()
        {

            CreateMethods = new LcCreateMethod[3];
            CreateMethods[0] = new LcCreateMethod()
            {
                Name = "CreateRectang",
                Description = "创建矩形",
                Steps = new LcCreateStep[]
                {
                    new LcCreateStep { Name=  "Step0", Options= "REXTANG指定第一个角点获[倒角(C)/标高（E）/圆角（F）/厚度（T）宽度（W）]:" },
                    new LcCreateStep { Name=  "Step1", Options= "REXTANG指定另一个角点或[面积(A)/尺寸(D)/旋转(R)]:" },
                    new LcCreateStep { Name=  "Step2", Options= "REXTANG输入以当前单位计算的矩形面积:" },
                    new LcCreateStep { Name=  "Step3", Options= "REXTANG计算矩形标注时依据[长度（L）宽度（W）]:" },
                    new LcCreateStep { Name=  "Step4", Options= "REXTANG输入矩形长度:" },
                    new LcCreateStep { Name=  "Step5", Options= "REXTANG输入矩形宽度:" },
                }
            };


         







            //CreateMethods[1] = new LcCreateMethod()
            //{
            //    Name = "CreateRectang",
            //    Description = "创建正方形",
            //    Steps = new LcCreateStep[]
            //    {
            //        new LcCreateStep { Name=  "Step0", Options= "REXTANG指定第一个角点获[倒角(C)/标高（E）/圆角（F）/厚度（T）宽度（W）]:" },
            //        new LcCreateStep { Name=  "Step1", Options= "REXTANG指定另一个角点或[面积(A)/尺寸(D)/旋转(R)]:" },
            //        new LcCreateStep { Name=  "Step2", Options= "REXTANG输入以当前单位计算的矩形面积:" },

            //    }
            //};

        }




        internal static void Initilize()
        {
            ElementActions.Rectang = new RectangAction();
            LcDocument.ElementActions.Add(BuiltinElementType.Rectang, ElementActions.Rectang);

        }
        private InElementsInputer InElementsInputer { get; set; }
        private ElementSetInputer ElementInputers { get; set; }
        private ElementInputer ElementInputer { get; set; }
        private CmdTextInputer CmdTextInputer { get; set; }
        private PointInputer PointInputer { get; set; }
        private RectangAction() { }
        public RectangAction(IDocumentEditor docEditor) : base(docEditor)
        {
            this.commandCtrl.WriteInfo("命令：RECTANG");
        }



        public async void ExecCreate(string[] args = null)
        {
            this.StartCreating();
            this.Segments = new List<PlineSegment>();   
            this.PointInputer = new PointInputer(this.docEditor);
            var curMethod = CreateMethods[0];
            var step0 = curMethod.Steps[0];
            var result0 = await PointInputer.Execute(step0.Options);
            if (PointInputer.isCancelled)
            {
                this.Cancel();
                return;
            }
            this.firstPoint = (Vector2)result0.ValueX;
            var step1 = curMethod.Steps[1];
            var result1 = await PointInputer.Execute(step1.Options);
            if (PointInputer.isCancelled)
            {
                this.Cancel();
                return;
            }
            if (result1.ValueX == null)
            {

                if (result1.Option.ToUpper() != "A")
                {
                    this.Cancel();
                    return;
                }

                
                if (result1.Option.ToUpper() == "A")
                {
                    var step2 = curMethod.Steps[2];
                    var result2 = await PointInputer.Execute(step2.Options);
                   
                    string resultString2 = result2.Option.ToString();
                    double.TryParse(resultString2, out double Area);


                    var step3 = curMethod.Steps[3];
                    var result3 = await PointInputer.Execute(step3.Options);
                    if (PointInputer.isCancelled)
                    {
                        this.Cancel();
                        return;
                    }



                    if (result3.Option.ToUpper() == "L")
                    {
                        var step4 = curMethod.Steps[4];
                        var result4 = await PointInputer.Execute(step4.Options);
                        if (PointInputer.isCancelled)
                        {
                            this.Cancel();
                            return;
                        }
                        string resultString4 = result4.Option.ToString();
                        double.TryParse(resultString4, out double Long);
                        double Width4 = Area / Long + Area % Long;

                        //生成四个点坐标（bottomLeft=Fpoint;   bottomRight.x=Fpoint.x+Long,bottomRight.y=Fpoint.y;  topLeft.x=Fpoint.x,topLeft.y=Fpoint.y+Long2;    topRight.x=Fpoint.x+long,topRight.y=Fpoint.y+Long2)
                        var mp = this.vportRt.PointerMovedPosition.ToVector2d();
                        var secPoint = this.vportRt.ConvertScrToWcs(mp);
                        Vector2 bottomLeft = (Vector2)result0.ValueX;
                        Vector2 bottomRight = new Vector2(bottomLeft.X + Long, bottomLeft.Y);
                        Vector2 topLeft = new Vector2(bottomLeft.X, bottomLeft.Y + Width4);
                        Vector2 topRight = new Vector2(bottomRight.X, topLeft.Y);




                        // Create rectangle segments
                        PlineSegment seg1 = new PlineSegment();
                        seg1.Start = topLeft;
                        seg1.End = topRight;
                        seg1.Type = PlineSegmentType.Line;
                        Segments.Add(seg1);

                        PlineSegment seg2 = new PlineSegment();
                        seg2.Start = topRight;
                        seg2.End = bottomRight;
                        seg2.Type = PlineSegmentType.Line;
                        Segments.Add(seg2);

                        PlineSegment seg3 = new PlineSegment();
                        seg3.Start = bottomRight;
                        seg3.End = bottomLeft;
                        seg3.Type = PlineSegmentType.Line;
                        Segments.Add(seg3);

                        PlineSegment seg4 = new PlineSegment();
                        seg4.Start = bottomLeft;
                        seg4.End = topLeft;
                        seg4.Type = PlineSegmentType.Line;
                        Segments.Add(seg4);
                    }

                    if (result3.Option.ToUpper() == "W")
                    {
                        var step5 = curMethod.Steps[5];
                        var result5 = await PointInputer.Execute(step5.Options);
                        if (PointInputer.isCancelled)
                        {
                            this.Cancel();
                            return;
                        }
                        string resultString5 = result5.Option.ToString();
                        double.TryParse(resultString5, out double Width);
                        double Long5 = Area / Width + Area % Width;

                        //生成四个点坐标（bottomLeft=Fpoint;   bottomRight.x=Fpoint.x+Long,bottomRight.y=Fpoint.y;  topLeft.x=Fpoint.x,topLeft.y=Fpoint.y+Long2;    topRight.x=Fpoint.x+long,topRight.y=Fpoint.y+Long2)
                        var mp = this.vportRt.PointerMovedPosition.ToVector2d();
                        var secPoint = this.vportRt.ConvertScrToWcs(mp);
                        Vector2 bottomLeft = (Vector2)result0.ValueX;
                        Vector2 bottomRight = new Vector2(bottomLeft.X + Long5, bottomLeft.Y);
                        Vector2 topLeft = new Vector2(bottomLeft.X, bottomLeft.Y + Width);
                        Vector2 topRight = new Vector2(bottomRight.X, topLeft.Y);

                        // Create rectangle segments
                        PlineSegment seg1 = new PlineSegment();
                        seg1.Start = topLeft;
                        seg1.End = topRight;
                        seg1.Type = PlineSegmentType.Line;
                        Segments.Add(seg1);

                        PlineSegment seg2 = new PlineSegment();
                        seg2.Start = topRight;
                        seg2.End = bottomRight;
                        seg2.Type = PlineSegmentType.Line;
                        Segments.Add(seg2);

                        PlineSegment seg3 = new PlineSegment();
                        seg3.Start = bottomRight;
                        seg3.End = bottomLeft;
                        seg3.Type = PlineSegmentType.Line;
                        Segments.Add(seg3);

                        PlineSegment seg4 = new PlineSegment();
                        seg4.Start = bottomLeft;
                        seg4.End = topLeft;
                        seg4.Type = PlineSegmentType.Line;
                        Segments.Add(seg4);
                    }


                }



            }
            else
            {

                // Calculate rectangle vertices
                Vector2 topLeft = new Vector2(Math.Min(((Vector2)result0.ValueX).X, ((Vector2)result1.ValueX).X), Math.Max(((Vector2)result0.ValueX).Y, ((Vector2)result1.ValueX).Y));
                Vector2 bottomRight = new Vector2(Math.Max(((Vector2)result0.ValueX).X, ((Vector2)result1.ValueX).X), Math.Min(((Vector2)result0.ValueX).Y, ((Vector2)result1.ValueX).Y));
                Vector2 topRight = new Vector2(bottomRight.X, topLeft.Y);
                Vector2 bottomLeft = new Vector2(topLeft.X, bottomRight.Y);

                // Create rectangle segments
                PlineSegment seg1 = new PlineSegment();
                seg1.Start = topLeft;
                seg1.End = topRight;
                seg1.Type = PlineSegmentType.Line;
                Segments.Add(seg1);

                PlineSegment seg2 = new PlineSegment();
                seg2.Start = topRight;
                seg2.End = bottomRight;
                seg2.Type = PlineSegmentType.Line;
                Segments.Add(seg2);

                PlineSegment seg3 = new PlineSegment();
                seg3.Start = bottomRight;
                seg3.End = bottomLeft;
                seg3.Type = PlineSegmentType.Line;
                Segments.Add(seg3);

                PlineSegment seg4 = new PlineSegment();
                seg4.Start = bottomLeft;
                seg4.End = topLeft;
                seg4.Type = PlineSegmentType.Line;
                Segments.Add(seg4);

            }
          
            CreateRectang(Segments);
            
            this.EndCreating();
        }

       




        private void CreateRectang(List<PlineSegment> seg)
        {
            if (seg == null || seg.Count != 4)
            {
                // 如果线段列表为空或线段数量不为4，则无法创建矩形
                return;
            }
            var doc = this.docRt.Document;
            DocumentManager.CurrentRecorder.BeginAction("PolyLine");
            var PolyLine = doc.CreateObject<LcPolyLine>();
            PolyLine.IsClosed = true;

            PolyLine.Segments = seg;

            doc.ModelSpace.InsertElement(PolyLine);
            this.docRt.Action.ClearSelects();
            DocumentManager.CurrentRecorder.EndAction();
 

        }
       
        public override void DrawAuxLines(SKCanvas canvas)
        {
            if (this.firstPoint != null)
            {
                var mp = this.vportRt.PointerMovedPosition.ToVector2d();
                var secPoint = this.vportRt.ConvertScrToWcs(mp);
                Vector2 topLeft = new Vector2(Math.Min(this.firstPoint.X, secPoint.X), Math.Max(this.firstPoint.Y, secPoint.Y));
                Vector2 bottomRight = new Vector2(Math.Max(this.firstPoint.X, secPoint.X), Math.Min(this.firstPoint.Y, secPoint.Y));
                Vector2 topRight = new Vector2(bottomRight.X, topLeft.Y);
                Vector2 bottomLeft = new Vector2(topLeft.X, bottomRight.Y);

                DrawAuxLine(canvas, topLeft, topRight, Constants.auxElementPen);
                DrawAuxLine(canvas, topRight, bottomRight, Constants.auxElementPen);
                DrawAuxLine(canvas, bottomRight, bottomLeft, Constants.auxElementPen);
                DrawAuxLine(canvas, bottomLeft, topLeft, Constants.auxElementPen);
            }
        }

        private void DrawAuxLine(SKCanvas canvas, Vector2 p0, Vector2 p1, SKPaint sKPaint)
        {
            var sk_pre = this.vportRt.ConvertWcsToScr(p0).ToSKPoint();
            var sk_p = this.vportRt.ConvertWcsToScr(p1).ToSKPoint();
            //辅助元素的颜色 
            canvas.DrawLine(sk_pre, sk_p, sKPaint);
            //辅助曲线的颜色，包括辅助长度，辅助角度等

        }

      

       







        //（cad里面始终是起始点的第一象限画矩形，L对应x轴，W对应y轴）
        //将这个方法应用到上面的步骤方法中，步骤方法确定L和W
        //将输入的数据传入Long
        //记另一边为Long2，Long2=Area/Long+Area%Long

        //判断如果输入的是L，则L=Long，W=Long2
        //生成四个点坐标（bottomLeft=Fpoint;   bottomRight.x=Fpoint.x+Long,bottomRight.y=Fpoint.y;  topLeft.x=Fpoint.x,topLeft.y=Fpoint.y+Long2;    topRight.x=Fpoint.x+long,topRight.y=Fpoint.y+Long2)

        //判断如果输入的是W，则W=Long，L=Long2
        //生成四个点坐标（bottomLeft=Fpoint;   bottomRight.x=Fpoint.x+Long2,bottomRight.y=Fpoint.y;  topLeft.x=Fpoint.x,topLeft.y=Fpoint.y+Long;    topRight.x=Fpoint.x+long2,topRight.y=Fpoint.y+Long)

        //将四个点记录下来，此方法结束
        //把四个点传入渲染成矩形






    }
}


